package com.mccken.rapid.core;

import com.mccken.rapid.common.constants.RapidBufferHelper;
import com.mccken.rapid.core.netty.NettyHttpClient;
import com.mccken.rapid.core.netty.NettyHttpServer;
import com.mccken.rapid.core.netty.processor.NettyBatchEventProcessor;
import com.mccken.rapid.core.netty.processor.NettyCoreProcessor;
import com.mccken.rapid.core.netty.processor.NettyMpmcProcessor;
import com.mccken.rapid.core.netty.processor.NettyProcessor;

import lombok.extern.slf4j.Slf4j;

/**
 * @program: rapid_gateway
 * @description: 容器生命周期
 * @author: mccken
 * @create: 2022-01-03 18:51
 **/
@Slf4j
public class RapidContainer implements LifeCycle {
	
	private final RapidConfig rapidConfig; // 核心配置类
	
	private NettyProcessor nettyProcessor;  // 核心处理类
	
	private NettyHttpServer nettyHttpServer; // 接收http请求的server
	
	private NettyHttpClient nettyHttpClient; // http转发的核心类
	
	public RapidContainer(RapidConfig rapidConfig) {
		this.rapidConfig = rapidConfig;
		
		init();
	}

	/**
	 * 1. 构建核心处理器
	 * 2. 是否开启缓存
	 */
	@Override
	public void init() {
		// 1. 构建核心处理器
		NettyCoreProcessor nettyCoreProcessor  = new NettyCoreProcessor();

		// 2. 是否开启缓存
		String bufferType = rapidConfig.getBufferType();
		if (RapidBufferHelper.isFlusher(bufferType)) {
			nettyProcessor = new NettyBatchEventProcessor(rapidConfig, nettyCoreProcessor);
		} else if (RapidBufferHelper.isMpmc(bufferType)) {
			nettyProcessor = new NettyMpmcProcessor(rapidConfig,nettyCoreProcessor, true);
		} else {
			nettyProcessor = nettyCoreProcessor;
		}
		
		// 3. 创建NettyHttpServer
		nettyHttpServer = new NettyHttpServer(rapidConfig,nettyProcessor);
		
		// 4. 创建NettyHttpClient
		nettyHttpClient = new NettyHttpClient(rapidConfig, nettyHttpServer.getEventLoopGroupWork());
	}

	@Override
	public void start() {
		nettyProcessor.start();
		nettyHttpServer.start();
		nettyHttpClient.start();
		log.info("#RapidContainer start#");
	}

	@Override
	public void shutdown() {
		nettyProcessor.shutdown();
		nettyHttpServer.shutdown();
		nettyHttpClient.shutdown();
		log.info("#RapidContainer shutdown#");
	}
}
